#!/bin/bash
python_dependency(){
	python -c "import sys,$1" 2>/dev/null	
}

#############################################################

clear
service="logsalt"
starter=$(echo $(pwd)"/server/classes/main.py" | sed -r 's/\//\\\//g')
groups_conf=$(echo $(pwd)"/server/conf/groups.json")


echo -n "checking OS Requirements... "
if [ -f /etc/redhat-release ] ; then
	os="redhat"	
elif [[ $(uname -a) =~ .*ubuntu.* ]] ; then
	os="ubuntu"
else
	echo -n "$(tput setaf 1)Not supported OS$(tput sgr0)"
fi
echo -n "$(tput setaf 2)OK$(tput sgr0)"
echo

echo -n "checking privilages ..."
[ $(whoami) != 'root' ] && echo "Not Previlage to run this script. Must be $(tput setaf 1)root$(tput sgr0)" && exit 1
echo -n "$(tput setaf 2)OK$(tput sgr0)"
echo

fails=0
python_modules=("sqlalchemy itertools paramiko termcolor sh ConfigParser")
for m in $python_modules ; do
	echo -n "checking python dependencies for $m ... "
	python_dependency "$m"
	if [ "$?" -eq 0 ] ; then
		echo -n "$(tput setaf 2)OK$(tput sgr0)"
	else
		echo -n "$(tput setaf 1)Fail$(tput sgr0)"
		((fails++))
	fi
	echo
done

[ $fails -gt 0 ] && echo "$(tput setaf 1)Please Install Missing python packages.$(tput sgr0)" && exit 1

echo -e "####	groups.json	###\n# insert here groups definitions. see examples.json file\n\n\n{\"groups\":{\n\n\t}\n}\n" > $groups_conf


echo -n "adding logsalt as service..."
cat init | sed -r "s/starter=/starter=\"$starter\"/g" 1>/etc/init.d/$service 2>/dev/null
[ "$?" -gt 0 ] && echo -n "$(tput setaf 1)Fail$(tput sgr0)" && exit 1

chmod 775 /etc/init.d/$service

if [ $os == "redhat" ] ; then
	chkconfig --add logsalt
else 
	update-rc.d logsalt defaults 98 02
fi
[ "$?" -gt 0 ] && echo -n "$(tput setaf 1)Fail$(tput sgr0)" && exit 1

if [ $os == "redhat" ] ; then
	chkconfig logsalt on
	[ "$?" -gt 0 ] && echo -n "$(tput setaf 1)Fail$(tput sgr0)" && exit 1

	echo -n "$(tput setaf 2)OK$(tput sgr0)"
	echo

	echo "service running on default runlevels :"
	chkconfig --list | grep --color=auto logsalt
fi

echo
echo "to activate type:"
echo "service logsalt (start|stop|restart)"
echo
echo "other switches can be found :"
echo $(pwd)"/server/classes/main.py -h"
echo 
echo "*****************************************************************************"


